package com.example.shangguigu.kaiser;

/**
 * @DESCRIPTION: 凯撒移位加密Demo
 * @USER: shg
 * @DATE: 2023/2/22 16:31
 */
public class KaiserDemo {

    public static void main(String[] args) {

        // 明文
        String sourceData = "Hello World";
        // 密钥
        int key = 8003;

        String encrypt = kaiserEncrypt(sourceData, key);
        System.out.println("加密后数据：" + encrypt);

        String decrypt = kaiserDecrypt(encrypt, key);
        System.out.println("解密后数据：" + decrypt);

    }

    /**
     * 凯撒解密(左移3位)
     *
     * @param ciphertext
     */
    public static String kaiserDecrypt(String ciphertext, int key) {
        char[] chars = ciphertext.toCharArray();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < chars.length; i++) {
            int x = chars[i];
            x = x - key;
            char newX = (char) x;
            sb.append(newX);
        }
        // System.out.println("密文："+ciphertext);
        // System.out.println("明文："+sb.toString());
        return sb.toString();
    }

    /**
     * 凯撒加密(右移3位)
     */
    public static String kaiserEncrypt(String source, int key) {
        char[] chars = source.toCharArray();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < chars.length; i++) {
            int x = chars[i];
            x = x + key;
            char newX = (char) x;
            sb.append(newX);
        }
        // System.out.println("原始字符串："+source);
        // System.out.println("右移三位后的加密字符串："+sb.toString());
        return sb.toString();
    }
}
